var express = require('express');
const mongoose = require('mongoose');

var router = express.Router();

// 连接数据库
mongoose.connect('mongodb://localhost:27017/h51903', { useNewUrlParser: true });
// 创建数据模型
const User = mongoose.model('user', {
  username: String,
  password: String
})

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/register.do', (req, res, next) => {
  // 获取 post 请求主体中传递的数据
  const { username, password } = req.body

  /* 连接数据库，保存到集合中 */
  // 根据数据类型，创建对象
  const user = new User({username, password})
  // 保存到数据库中
  user.save().then(data => {
    console.log(data)
    res.json(data)
  }).catch()
})

module.exports = router;
